<template>
  <el-dialog v-model="visible" :title="title" width="1100" show-footer show-zoom resize :close-on-click-modal="false"
    :close-on-press-escape="false" @close="close">
    <template #default>
      <el-form ref="formRef" :rules="rules" :model="form" label-align="right" label-width="100" size="default">

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="调拨单号">
              {{ form.backup_warehouse_order_no }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="调出仓">{{ form.out_warehouse_name }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="调入仓">{{ form.in_warehouse_name }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="海外仓出库单">{{ form.send_shipment_id }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="海外仓入库单">{{ form.shipment_id }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注">{{ form.remark }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <vxe-table :data="form.detail" :round="true" height="300">
        <vxe-column field="name" title="调出仓SKU" width="250">
          <template #default="{ row }">
            <div>SKU：{{ row.sku }}</div>
            <div>自定义SKU：{{ row.custom_sku }}</div>
            <div>第三方SKU：{{ row.send_fn_sku }}</div>
          </template>
        </vxe-column>
        <vxe-column field="num" title="调入仓SKU"  width="200">
          <template #default="{ row }">
            <div>渠道SKU：{{ row.to_seller_sku }}</div>
            <div>FNSKU：{{ row.to_fn_sku }}</div>
          </template>
        </vxe-column>
        <vxe-column field="owner_name" title="货主"></vxe-column>
        <vxe-column field="sku_cn_title" title="产品名称"  width="200"></vxe-column>
        <vxe-column field="adjust_num" title="调拨数量"></vxe-column>
        <vxe-column field="apply_num" title="发货数量"></vxe-column>
      </vxe-table>
    </template>

    <template #footer>
      <template v-if="handleType == 'view'">
        <div class="flex justify-center py-2">
          <el-button type="" @click="close">关 闭</el-button>
        </div>
      </template>
    </template>
  </el-dialog>
</template>
<script setup name="ComModal">
import { getAdjustOutDetail } from '../api/index'
import { getSKULocation } from '@/api/public'
import { reactive, ref, toRefs, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import SelectWarehouse from '@/components/SelectWarehouse'

const visible = ref(false)
const loading = ref(false)
const formRef = ref(null)
const emits = defineEmits(['query'])

const props = defineProps({
  wareDataList: {
    type: Array,
    default: [],
  },
})

const data = reactive({
  form: {},
  title: '新增',
  handleType: null,
  rules: {
    out_warehouse_id: [{
      required: true, message: '请选择所属仓库', trigger: 'blur'
    }],
    in_warehouse_id: [{
      required: true, message: '请选择所属仓库', trigger: 'blur'
    }],
  },
})
const { form, title, handleType, rules } = toRefs(data)

const statusMap = new Map([
  ['add', '新增'],
  ['edit', '编辑'],
  ['view', '查看'],
  ['out', '出库'],
])

const open = (type, id) => {
  title.value = statusMap.get(type)
  handleType.value = type
  visible.value = true
  if (id) getDetail(id)
}

const initForm = () => {
  form.value = getForm()
}
// 初始化
const getForm = () => {
  return {
    detail: [
      {
        sku: "",//sku
        custom_sku: "",//自定义sku
        base_sku_code: "",//商品编码
        adjust_num: '',//调拨数量
        location_id: "",//货位编码
        remark: "",//备注
        location: []
      }
    ]
  }
}

onMounted(() => {
  initForm()
})

const getDetail = async (id) => {
  try {
    const res = await getAdjustOutDetail({
      id
    })
    form.value = res.data
  } catch (e) {
    throw Error(e)
  }
}

const addRow = async () => {
  form.value.detail.push({
    sku: "",//sku
    custom_sku: "",//自定义sku
    base_sku_code: "",//商品编码
    adjust_num: '',//调拨数量
    location_code: "",//货位编码
    remark: "",//备注
    locationList: []
  })
}

const deleteRow = (index) => {
  if (form.value.detail.length <= 1) return
  form.value.detail.splice(index, 1)
}

const changeWarehouse = () => {
  form.value.detail.forEach(item => {
    item.location = []
    item.location_id = ''
    item.num = ''
  })
}


const changeSkU = async (row) => {
  if (!row.sku) {
    ElMessage.error('输入sku')
    return
  }
  if (!form.value.out_warehouse_id) {
    ElMessage.error('请选择调出仓')
    return
  }
  try {
    const res = await getSKULocation({
      sku: row.sku,
      warehouse_id: form.value.out_warehouse_id,
      type: 1
    })
    row.sku = res.data.sku
    row.location = res.data.location
    row.custom_sku = res.data.custom_sku || '32323sses'
    row.sku_cn_title = res.data.sku_cn_title
    row.base_sku_code = res.data.base_sku_code
  } catch (e) {
    throw Error(e)
  }
}

const changeLocation = (val, row) => {
  const checkItem = row.location.find(item => item.location_id == val)
  if (checkItem == undefined) return
  row.num = checkItem.num
}

const save = () => {
  if (!formRef.value) return
  formRef.value.validate((valid) => {
    if (valid) {
      loading.value = true
      if (form.value.id) {
        updateAdjustOut(form.value)
          .then((res) => {
            ElMessage.success(res.message)
            emits('query')
            close()
          })
          .finally((e) => {
            loading.value = false
          })
      } else {
        saveAdjustOut(form.value)
          .then((res) => {
            ElMessage.success(res.message)
            emits('query')
            close()
          })
          .finally((e) => {
            loading.value = false
          })
      }
    }
  })
}

const stockOut = async () => {
  let formData = {}
  formData.id = form.value.id
  formData.detail = form.value.detail.map(i => {
    return {
      id: i.id,
      out_warehouse_num: i.out_warehouse_num
    }
  })
  try {
    const res = await outAdjustOut(formData)
    ElMessage.success(res.message)
    emits('query')
    close()
  } catch (e) {
    throw Error(e)
  }
}
const close = () => {
  initForm()
  visible.value = false
}
defineExpose({ open })
</script>
<style lang="scss" scoped>
.borderNone {
  :deep(.el-input__wrapper) {
    border: none;
    box-shadow: none
  }
}
</style>
